import { userApi } from '/api/user'

Page({
  data: {
    tagList: [],
    userTags: [] as any[],
    ids: [] as number[],
  },
  async onLoad() {
    this.getInfo()
  },
  async getInfo() {
    const userTags = await userApi.getUserTags()
    const tagList = await userApi.getTags()
    const ids = [] as any

    userTags.forEach((item: any) => {
      ids.push(item.id)
    }),
      this.setData({
        tagList,
        userTags,
        ids,
      })
  },
  /** 添加标签 */
  async choose(e: WechatMiniprogram.CustomEvent) {
    const {
      data: { userTags },
    } = this
    const {
      currentTarget: {
        dataset: { id, item },
      },
    } = e
    /** 最多选五个标签 */
    if (userTags.length === 5) {
      wx.showToast({
        title: '最多选择五个标签哦',
        icon: 'none',
      })
      return
    }
    if (
      userTags.find((item) => {
        return item.id === id
      })
    ) {
      wx.showToast({
        title: '请勿重复添加标签',
        icon: 'none',
      })
      return
    }
    await userApi.addTags(id)
    this.changeTags(item, 'add')
  },
  /** 删除标签 */
  async delete(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id, item },
      },
    } = e
    await userApi.deletTags(id)
    this.changeTags(item, 'delete')
  },
  changeTags(item: { id: any; name: string }, methods: string) {
    /** 改变本页数据 */
    const {
      data: { userTags, ids },
    } = this
    const itemType = userTags.find((items) => {
      return item.id === items.id
    })
    methods === 'add' ? ids.push(item.id) : ids.splice(ids.indexOf(item.id), 1)
    methods === 'add' ? userTags.push(item) : userTags.splice(userTags.indexOf(itemType), 1)
    this.setData({ userTags, ids })
    /** 改变上一页的数据 */
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    lastpage.setData({
      userTags,
    })
  },
})
